const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const autoprefixer = require('autoprefixer')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const os = require('os')
const MomentLocalesPlugin = require('moment-locales-webpack-plugin')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const merge = require('webpack-merge')

const NODE_ENV = process.env.NODE_ENV
console.info(`====== 当前环境：${NODE_ENV} ======`)

const config = {
  // entry: { index: [path.resolve(__dirname, './src/babel.js')] },
  entry: { index: [path.resolve(__dirname, './src/index1.js')] },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename:
      NODE_ENV === 'production'
        ? 'js/[name].[chunkhash:8].js'
        : 'js/[name].[hash:8].js' //以name+chunk内容的md5值作为输出的文件名
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve(__dirname, 'src'),
        use: [
          {
            loader: 'thread-loader',
            options: {
              // 开销大的时候开启多线程，用node获取cpu数启动
              workers: os.cpus().length - 1
            }
          },
          {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  '@babel/preset-env',
                  {
                    debug: false,
                    modules: false, //Babel的预案（preset）默认会将任何模块类型都转译成CommonJS类型,此设置改为es6模块范式这样可以摇树优化
                    targets: {
                      browsers: ['> 1%', 'last 2 versions', 'not ie <= 8']
                    },
                    // useBuiltIns: 'entry',//按浏览器环境导入
                    useBuiltIns: 'usage', //按需导入
                    corejs: { version: 2 }
                  }
                ],
                ['@babel/react']
              ],
              plugins: [
                ['@babel/plugin-proposal-decorators', { legacy: true }],
                ['@babel/plugin-proposal-class-properties', { loose: true }], //根据报错加了loose就好了 原理还没看
                'dynamic-import-webpack'
              ],
              cacheDirectory: true
            }
          }
          // 你的高开销的loader放置在此 (e.g babel-loader)
        ],
        exclude: path.resolve(__dirname, 'node_modules')
      },
      {
        test: /\.css/,
        use: [
          NODE_ENV === 'production'
            ? MiniCssExtractPlugin.loader
            : 'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: '10240', //小于10k进行base64转化
              name() {
                return '[path][name].[ext]'
              }
            }
          }
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ['file-loader']
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader:
              NODE_ENV === 'production'
                ? MiniCssExtractPlugin.loader
                : 'style-loader'
          },
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer({
                  browsers: ['last 3 versions', '> 1%']
                })
              ]
            }
          },
          {
            loader: 'sass-loader'
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader:
              NODE_ENV === 'production'
                ? MiniCssExtractPlugin.loader
                : 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer({
                  browsers: ['last 3 versions', '> 1%']
                })
              ]
            }
          },
          {
            loader: 'less-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'public/index.html'), // html模板路径
      minify: {
        // 压缩HTML文件yarn
        removeComments: true, // 移除HTML中的注释
        collapseWhitespace: true // 删除空白符与换行符
      }
    }),
    new MomentLocalesPlugin({
      localesToKeep: ['zh-cn']
    }),
    new CaseSensitivePathsPlugin()
  ],
  resolve: {
    modules: [path.resolve(__dirname, 'node_modules')],
    extensions: ['.js', '.json', '.jsx'], //查找时import a默认给他加上后缀进行尝试匹配
    alias: {
      '@': path.resolve('./src'),
      Styles: path.resolve('./src/common/styles'),
      Comps: path.resolve('./src/components'),
      Imgs: path.resolve('./src/assets/images'),
      ApiHost: path.resolve('./config/api-host.dev'),
      ApiMapper: path.resolve('./src/common/api-mapper'),
      Utils: path.resolve('./src/utils')
      // 'core-js': path.resolve('node_modules/core-js/modules')//解决新版本env引起的库问题
    }
  },
  watchOptions: {
    //不监听的 node_modules 目录下的文件
    ignored: /node_modules/,
  }
}

module.exports = config

// module.exports = () => {
//   console.log(config.resolve.alias)
//   delete config.resolve.alias['core-js']
//   return { entry: '1/index' }
// }
